package com.lzx.iteam.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.*;
import android.widget.TextView;
import com.lzx.iteam.R;
import com.lzx.iteam.provider.CloudDBOperation;
import com.lzx.iteam.util.AndroidRomUtil;
import com.lzx.iteam.util.PhoneNumberUtils;
import com.lzx.iteam.util.PreferenceUtil;
import com.lzx.iteam.util.StringUtil;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * **********************************
 * User: zhangshuai
 * Date: 2016年 01月 12日
 * Time: 下午3:46
 *
 * @QQ : 1234567890
 * **********************************
 */
public class CommonService extends Service {


    private TelephonyManager mTelManager;
    private PhoneCallListener mListener;
    private View mContactInfoView = null;
    private WindowManager mWindowManager = null;
    private WindowManager.LayoutParams mParams = null;
    private CloudDBOperation mCloudDBOperation;
    private PreferenceUtil mPreferenceUtil;
    private String mUid;
    private float mShowContactX;
    private float mShowContactY;

    public static final int CALL_SHOW_CONTACT_DISPLAY = 11;
    public static final int CALL_SHOW_CONTACT_CANCEL = 12;
    private static final String SHOW_CONTACT_X = "show_contact_x";
    private static final String SHOW_CONTACT_Y = "show_contact_y";


    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case CALL_SHOW_CONTACT_DISPLAY:
                    String  phone = (String) msg.obj;
                    Log.d("CommonService",phone);
                    showCallView(phone);
                    break;
                case CALL_SHOW_CONTACT_CANCEL:
                    if (mContactInfoView != null){
                        mWindowManager.removeViewImmediate(mContactInfoView);
                        mContactInfoView = null;
                        mPreferenceUtil.save(SHOW_CONTACT_X,mParams.x);
                        mPreferenceUtil.save(SHOW_CONTACT_Y,mParams.y);
                        Log.d("CommonService",mParams.x +"   save  "+ mParams.y);

                    }
                    break;
            }

        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mCloudDBOperation = new CloudDBOperation(this);
        mPreferenceUtil = PreferenceUtil.getInstance(this);
        mTelManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        mListener = new PhoneCallListener();
        mTelManager.listen(mListener, PhoneStateListener.LISTEN_CALL_STATE);
        mWindowManager = (WindowManager) getApplicationContext().getSystemService(WINDOW_SERVICE);

        // TODO 设置悬浮框的位置 和 属性
        mParams = new WindowManager.LayoutParams();

        // TODO 这两个小米系统用这个type 悬浮框不出来
        //mParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;// 系统提示window
        //mParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;

        // TODO 有的手机设置锁屏后显示不出来
        //mParams.type = WindowManager.LayoutParams.TYPE_TOAST;

        // TODO 能显示出来，但是获取不到焦点
        //mParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY;

        if(AndroidRomUtil.isMIUI()){
            mParams.type = WindowManager.LayoutParams.TYPE_TOAST;
        }else{
            mParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
        }
        mParams.format = PixelFormat.TRANSLUCENT;// 支持透明
        //mParams.format = PixelFormat.RGBA_8888;
        mParams.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE ;// 焦点
        mParams.width = ViewGroup.LayoutParams.WRAP_CONTENT;//窗口的宽和高
        mParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        mParams.gravity = Gravity.TOP + Gravity.LEFT;
        // TODO 查询最后滑动的位置
        int x = mPreferenceUtil.getInt(SHOW_CONTACT_X, 0);
        int y = mPreferenceUtil.getInt(SHOW_CONTACT_Y, 0);
        if (x != 0 || y != 0){
            mParams.x = x;
            mParams.y = y;
            Log.d("CommonService",mParams.x +"  old  "+ mParams.y);
        }else{
            mParams.x = 30;//窗口位置的偏移量
            mParams.y = 30;
            Log.d("CommonService",mParams.x +"   default  "+ mParams.y);
        }
        //mParams.alpha = 0.1f;//窗口的透明度
        Log.d("CommonService","onCreate");
    }

    // 监听通话状态
    public class PhoneCallListener extends PhoneStateListener{

        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            // TODO Auto-generated method stub
            switch (state) {
                /*判断手机目前是待机状态*/
                case TelephonyManager.CALL_STATE_IDLE:
                    mHandler.sendEmptyMessage(CALL_SHOW_CONTACT_CANCEL);
                    break;
                /*判断状态为通话中*/
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    break;

                /*判断状态为来电*/
                case TelephonyManager.CALL_STATE_RINGING:
                    if (StringUtil.isEmpty(incomingNumber)) {
                        return;
                    }
                    Message message = Message.obtain();
                    message.what = CALL_SHOW_CONTACT_DISPLAY;
                    message.obj = incomingNumber;
                    mHandler.sendMessage(message);
                    Log.d("CommonService",incomingNumber);
                    break;
            }
            super.onCallStateChanged(state, incomingNumber);
        }

    }

    /**
     * 显示悬浮框
     * @param phone
     */
    private void showCallView(String phone){
        try {
            mUid = mPreferenceUtil.getString(PreferenceUtil.CLIENT_USEID, "－1");
            List<String> contact = mCloudDBOperation.findOneContact(mUid,PhoneNumberUtils.cutPlus86Formatter(phone));
            Log.d("CommonService",contact.toString());
            if (contact.size() > 0){
                LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                mContactInfoView = inflater.inflate(R.layout.show_contact_layout, null);
                TextView contactPhone = (TextView) mContactInfoView.findViewById(R.id.show_tv_contact);
                contactPhone.setText(contact.get(1));
                TextView contactGroup = (TextView) mContactInfoView.findViewById(R.id.show_tv_group);
                contactGroup.setText(contact.get(0));
                if (!StringUtil.isEmpty(contact.get(2))){
                    TextView contactJob = (TextView) mContactInfoView.findViewById(R.id.show_tv_job);
                    contactJob.setText(contact.get(2));
                }

                // TODO 监听滑动的位置
                mContactInfoView.setOnTouchListener(new View.OnTouchListener() {

                    @Override
                    public boolean onTouch(View paramView, MotionEvent event) {

                        switch (event.getAction()) {
                            case MotionEvent.ACTION_DOWN:
                                mShowContactX = (int) event.getRawX();
                                mShowContactY = (int) event.getRawY();

                                break;
                            case MotionEvent.ACTION_MOVE:
                                float newX = event.getRawX();
                                float newY = event.getRawY();
                                float dX = newX - mShowContactX;
                                float dY = newY - mShowContactY;
                                mParams.x += dX;
                                mParams.y += dY;
                                //left
                                if (mParams.x < 0) {
                                    mParams.x = 0;
                                }
                                //top
                                if (mParams.y < 0) {
                                    mParams.y = 0;
                                }
                                //right
                                if (mParams.x > mWindowManager.getDefaultDisplay().getWidth() - mContactInfoView.getWidth()) {
                                    mParams.x = mWindowManager.getDefaultDisplay().getWidth() - mContactInfoView.getWidth();
                                }
                                //bottom
                                if (mParams.y > mWindowManager.getDefaultDisplay().getHeight() - mContactInfoView.getHeight()) {
                                    mParams.y = mWindowManager.getDefaultDisplay().getHeight() - mContactInfoView.getHeight();
                                }
                                mWindowManager.updateViewLayout(mContactInfoView, mParams);
                                //update start position
                                mShowContactX = event.getRawX();
                                mShowContactY = event.getRawY();
                                break;

                            case MotionEvent.ACTION_UP:
                                break;
                        }
                        return true;
                    }
                });
                mWindowManager.addView(mContactInfoView,mParams);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mTelManager.listen(mListener, PhoneStateListener.LISTEN_NONE);
    }
}
